package cc.mrbird.febs.system.controller;


import cc.mrbird.febs.common.annotation.ControllerEndpoint;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.DeptTree;
import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.common.exception.FebsException;
import cc.mrbird.febs.common.utils.SortUtil;
import cc.mrbird.febs.system.entity.Course;
import cc.mrbird.febs.system.entity.Dept;
import cc.mrbird.febs.system.entity.User;
import cc.mrbird.febs.system.entity.UserDept;
import cc.mrbird.febs.system.service.IDeptService;
import cc.mrbird.febs.system.service.IUserDeptService;
import cc.mrbird.febs.system.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author MrBird
 */
@Slf4j
@RestController
@RequestMapping("dept")
public class DeptController extends BaseController {

    @Autowired
    private IDeptService deptService;

    @Resource
    private IUserDeptService userDeptService;

    @Resource
    private IUserService userService;

    @GetMapping("select/tree")
    @ControllerEndpoint(exceptionMessage = "获取部门树失败")
    public List<DeptTree<Dept>> getDeptTree() throws FebsException {
        return this.deptService.findDepts();
    }

    @GetMapping("tree")
    @ControllerEndpoint(exceptionMessage = "获取部门树失败")
    public FebsResponse getDeptTree(Dept dept) throws FebsException {
        List<DeptTree<Dept>> depts = this.deptService.findDepts(dept);
        return new FebsResponse().success().data(depts);
    }

    @PostMapping
    @RequiresPermissions("dept:add")
    @ControllerEndpoint(operation = "新增部门", exceptionMessage = "新增部门失败")
    public FebsResponse addDept(@Valid Dept dept) {
        this.deptService.createDept(dept);
        return new FebsResponse().success();
    }

    @GetMapping("delete/{deptIds}")
    @RequiresPermissions("dept:delete")
    @ControllerEndpoint(operation = "删除部门", exceptionMessage = "删除部门失败")
    public FebsResponse deleteDepts(@NotBlank(message = "{required}") @PathVariable String deptIds) throws FebsException {
        String[] ids = deptIds.split(StringPool.COMMA);
        this.deptService.deleteDepts(ids);
        return new FebsResponse().success();
    }

    @PostMapping("update")
    @RequiresPermissions("dept:update")
    @ControllerEndpoint(operation = "修改部门", exceptionMessage = "修改部门失败")
    public FebsResponse updateDept(@Valid Dept dept) throws FebsException {
        this.deptService.updateDept(dept);
        return new FebsResponse().success();
    }

    @GetMapping("excel")
    @RequiresPermissions("dept:export")
    @ControllerEndpoint(exceptionMessage = "导出Excel失败")
    public void export(Dept dept, QueryRequest request, HttpServletResponse response) throws FebsException {
        List<Dept> depts = this.deptService.findDepts(dept, request);
        ExcelKit.$Export(Dept.class, response).downXlsx(depts, false);
    }

    //Teacher，老师管理
    /**
     * 根据当前登录用户（老师）
     * 去查询该老师拥有的班级，学生，课程信息
     *
     * @param dept
     * @param request
     * @return
     */
    @GetMapping("teacher/list")
    @RequiresPermissions("teacherDept:view")
    public FebsResponse teacherDeptList(Dept dept, QueryRequest request) {
        Page<Dept> page = new Page<>(request.getPageNum(), request.getPageSize());
        SortUtil.handlePageSort(request, page, "dept_id", FebsConstant.ORDER_ASC, false);
        User user = getCurrentUser();
        List<UserDept> userDeptList = userDeptService.list(new QueryWrapper<UserDept>().lambda().eq(UserDept::getUserId, user.getUserId()));
        List<Integer> collect = userDeptList.stream().map(UserDept::getDeptId).collect(Collectors.toList());
        IPage<Map<String, Object>> mapIPage = deptService.pageMaps(page, new QueryWrapper<Dept>().lambda().in(Dept::getDeptId, collect));
        List<Map<String, Object>> records = mapIPage.getRecords();
        for (Map<String, Object> record : records) {
            List<User> userList = userService.list(new QueryWrapper<User>().lambda().eq(User::getDeptId, record.get("DEPT_ID")));
            record.put("count", userList.size());
        }
        Map<String, Object> dataTable = getDataTable(mapIPage);
        return new FebsResponse().success().data(dataTable);
    }

    @GetMapping("select/student")
    @RequiresPermissions("deptStudent:view")
    public FebsResponse selectUserStudent(Integer deptId,User user,QueryRequest request){
        //查询，用户表的学生角色用户，状态用有效，且学生所在班级为传入的班级ID
        IPage<User> studentByDeptIdList = this.deptService.findStudentByDeptIdList(deptId, user, request);
        Map<String, Object> dataTable = getDataTable(studentByDeptIdList);
        return new FebsResponse().success().data(dataTable);
    }




}
